<template>
  <div class="countContainer" :class="{ isDark: isDark }">
    <div class="item">
      <span class="name">{{ $t("count.words") }}</span>
      <span class="value">{{ words }}</span>
    </div>
    <div class="item">
      <span class="name">{{ $t("count.nodes") }}</span>
      <span class="value">{{ num }}</span>
    </div>
  </div>
</template>

<script>
import { mapState } from "pinia"
import { useMind } from "@mind/store"

/**
 * @Desc: 字数及节点数量统计
 */

const countEl = document.createElement("div")
export default {
  name: "Count",
  data() {
    return {
      textStr: "",
      words: 0,
      num: 0
    }
  },
  computed: {
    ...mapState(useMind, ["isDark"])
  },
  created() {
    this.$bus.$on("init", () => {
      this.$bus.$on("data_change", this.onDataChange)
    })
  },
  beforeUnmount() {
    this.$bus.$off("data_change")
    this.$bus.$off("init")
  },
  methods: {
    /**
     * @Desc: 监听数据变化
     */
    onDataChange(data) {
      this.textStr = ""
      this.words = 0
      this.num = 0
      this.walk(data[0])
      countEl.innerHTML = this.textStr
      this.words = countEl.textContent.length
    },

    /**
     * @Desc: 遍历
     */
    walk(data) {
      this.num++
      this.textStr += String(data.data.text) || ""
      if (data.children && data.children.length > 0) {
        data.children.forEach((item) => {
          this.walk(item)
        })
      }
    }
  }
}
</script>

<style lang="less" scoped>
.countContainer {
  padding: 0 12px;
  background: hsla(0, 0%, 100%, 0.8);
  border-radius: 2px;
  opacity: 0.8;
  height: 22px;
  width: 120px;
  line-height: 22px;
  font-size: 12px;
  display: flex;

  &.isDark {
    background: #262a2e;

    .item {
      color: hsla(0, 0%, 100%, 0.6);
    }
  }

  .item {
    color: #555;
    margin-right: 15px;

    &:last-of-type {
      margin-right: 0;
    }

    .name {
      margin-right: 5px;
    }
  }
}
</style>
